package com.vegetable.modules.service.stock.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.modules.entity.stock.CostWeightChangeSource;
import com.vegetable.modules.mapper.stock.CostWeightChangeSourceMapper;
import com.vegetable.modules.service.stock.ICostWeightChangeChainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 成本单价变化链路查询服务实现类
 * </p>
 *
 * @author wangruijie
 * @since 2024-03-21
 */
@Slf4j
@Service
public class CostWeightChangeChainServiceImpl extends ServiceImpl<CostWeightChangeSourceMapper, CostWeightChangeSource> implements ICostWeightChangeChainService {

    @Override
    public List<CostWeightChangeSource> queryChainByTtid(String ttid) {
        if (ttid == null || ttid.trim().isEmpty()) {
            return null;
        }
        
        QueryWrapper<CostWeightChangeSource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ttid", ttid);
        queryWrapper.orderByAsc("operate_time");
        
        return this.list(queryWrapper);
    }
    
    @Override
    public ICostWeightChangeChainService.ChainDetailVO getChainDetail(String ttid) {
        if (ttid == null || ttid.trim().isEmpty()) {
            return null;
        }
        
        // 查询所有相关记录
        List<CostWeightChangeSource> changes = queryChainByTtid(ttid);
        if (changes == null || changes.isEmpty()) {
            return null;
        }
        
        // 创建VO对象
        ICostWeightChangeChainService.ChainDetailVO detailVO = new ICostWeightChangeChainService.ChainDetailVO();
        detailVO.setTtid(ttid);
        detailVO.setChanges(changes);
        detailVO.setTotalCount(changes.size());
        
        // 计算涉及的商品数量
        long commodityCount = changes.stream()
            .map(CostWeightChangeSource::getCommodityId)
            .distinct()
            .count();
        detailVO.setCommodityCount((int) commodityCount);
        
        // 计算总成本变化金额
        BigDecimal totalChangeAmount = changes.stream()
            .map(CostWeightChangeSource::getChangeAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        detailVO.setTotalChangeAmount(totalChangeAmount);
        
        // 获取首次和最后变化时间
        Date firstChangeTime = changes.stream()
            .map(CostWeightChangeSource::getOperateTime)
            .min(Date::compareTo)
            .orElse(null);
        detailVO.setFirstChangeTime(firstChangeTime);
        
        Date lastChangeTime = changes.stream()
            .map(CostWeightChangeSource::getOperateTime)
            .max(Date::compareTo)
            .orElse(null);
        detailVO.setLastChangeTime(lastChangeTime);
        
        return detailVO;
    }
}